package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/andybalholm/brotli"
)

var getMsgHeader = http.Header{
	"Host":            []string{"api.live.bilibili.com"},
	"Connection":      []string{"keep-alive"},
	"Accept":          []string{"application/json, text/plain, */*"},
	"User-Agent":      []string{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"},
	"Accept-Encoding": []string{"gzip, deflate, br"},
	"Accept-Language": []string{"zh-CN,zh;q=0.9"},
}

var getMsgUrl = "https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid=%d"

//  GetMsg 2021-08-31 22:16:17
//  @Description:
//  @param roomId int
//  @return rooms []Room
//  @return err error
func GetMsg(roomId int) (rooms []Room, err error) {
	if roomId == 0 {
		return
	}
	//8290796

	req, err := http.NewRequest(http.MethodGet, fmt.Sprintf(getMsgUrl, roomId), nil)
	if err != nil {
		return nil, err
	}
	req.Header = getMsgHeader

	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(brotli.NewReader(res.Body))
	if err != nil {
		return nil, err
	}
	result := &getHistoryMsg{}
	err = json.Unmarshal(body, result)
	if err != nil {
		return nil, err
	}
	if result.Code != 0 {
		return nil, errors.New(result.Message)
	}

	return result.Data.Room, nil
}

type getHistoryMsg struct {
	Code int `json:"code"`
	Data struct {
		Admin []interface{} `json:"admin"`
		Room  []Room        `json:"room"`
	} `json:"data"`
	Message string `json:"message"`
	Msg     string `json:"msg"`
}

type Room struct {
	Text        string        `json:"text"`
	DmType      int           `json:"dm_type"`
	UID         int           `json:"uid"`
	Nickname    string        `json:"nickname"`
	UnameColor  string        `json:"uname_color"`
	Timeline    string        `json:"timeline"`
	Isadmin     int           `json:"isadmin"`
	Vip         int           `json:"vip"`
	Svip        int           `json:"svip"`
	Medal       []interface{} `json:"medal"`
	Title       []string      `json:"title"`
	UserLevel   []interface{} `json:"user_level"`
	Rank        int           `json:"rank"`
	Teamid      int           `json:"teamid"`
	Rnd         string        `json:"rnd"`
	UserTitle   string        `json:"user_title"`
	GuardLevel  int           `json:"guard_level"`
	Bubble      int           `json:"bubble"`
	BubbleColor string        `json:"bubble_color"`
	Lpl         int           `json:"lpl"`
	CheckInfo   struct {
		Ts int    `json:"ts"`
		Ct string `json:"ct"`
	} `json:"check_info"`
	VoiceDmInfo struct {
		VoiceURL     string `json:"voice_url"`
		FileFormat   string `json:"file_format"`
		Text         string `json:"text"`
		FileDuration int    `json:"file_duration"`
		FileID       string `json:"file_id"`
	} `json:"voice_dm_info"`
	Emoticon interface{} `json:"emoticon"`
}
